(() => {
    let bilibiliLeftControls, bilibiliPlayer;
    let currentVideo = "";
    let currentVideoBookmarks = [];

    const fetchBookmarks = () => {
        return new Promise((resolve) => {
            chrome.storage.sync.get([currentVideo], (obj) => {
                resolve(obj[currentVideo] ? JSON.parse(obj[currentVideo]) : [])
            });
        });
    };

    const addNewBookmarkEventHander = async () => {
        const currentTime = bilibiliPlayer.currentTime;
        const newBookmark = {
            time : currentTime,
            desc : "书签 ：" + getTime(currentTime),
        };

        currentVideoBookmarks = await fetchBookmarks();

        chrome.storage.sync.set({
            [currentVideo] : JSON.stringify([...currentVideoBookmarks, newBookmark].sort((a, b) => a.time - b.time))
        });
    };

    const newVideoLoaded = async () => {

        const bookmarkBtnExists = document.getElementsByClassName("bookmark-btn")[0];

        currentVideoBookmarks = await fetchBookmarks();
        
        if(!bookmarkBtnExists){
            const bookmarkBtn = document.createElement("div");
            const bookmarkBtnImg = document.createElement("img");
            bookmarkBtnImg.style.cssText = "width:22px;height:22px";
            bookmarkBtnImg.src = chrome.runtime.getURL("assets/bookmark.png");
            bookmarkBtn.className = "bpx-player-ctrl-btn " + "bookmark-btn";
            bookmarkBtn.title = "Click to bookmark current timestamp";
            bookmarkBtn.append(bookmarkBtnImg);

            bilibiliLeftControls = document.getElementsByClassName("bpx-player-control-bottom-left")[0];
            bilibiliPlayer = document.getElementsByTagName('video')[0];
            bilibiliLeftControls.appendChild(bookmarkBtn);
            bookmarkBtn.addEventListener("click", addNewBookmarkEventHander);
        };
    };

    chrome.runtime.onMessage.addListener((obj, sender, response) => {
        console.log(obj);
        const { type, value, videoId } = obj;
        if (type === "NEW") {
            currentVideo = videoId;
            newVideoLoaded();
        } else if ( type === "PLAY") {
            bilibiliPlayer.currentTime = value;
        } else if ( type ==="DELETE") {
            console.log("DELETE");
            currentVideoBookmarks = currentVideoBookmarks.filter((b)=> b.time !=value);
            chrome.storage.sync.set({ [currentVideo]: JSON.stringify(currentVideoBookmarks)});

            response(currentVideoBookmarks);
        }

    })

    newVideoLoaded();
})();

const getTime = t => {
    var date = new Date(0);
    date.setSeconds(t);
    return date.toISOString().substring(11, 19)
}